package com.ls.config;

import com.ls.Interceptor.LoginInterceptor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration
public class CorsConfig implements WebMvcConfigurer {
    @Bean //交给容器管理
    public LoginInterceptor loginInterceptor() {
        return new LoginInterceptor();
    }

    /**
     * 拦截哪些请求：
     * 排除哪些请求(静态资源和登录不能拦截)，登录处理，验证码图片
     * @param registry
     */
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        //需要一个实现了拦截器功能的实例对象
        registry.addInterceptor(loginInterceptor())
                .addPathPatterns("/**") // 设置需要被拦截的资源
//                .excludePathPatterns("/api/**","/css/**","/images/**","/js/**","/lib/**", "/layui/**","/login","/captcha","/user/login");
                .excludePathPatterns("/api/**","/css/**","/images/**","/js/**","/lib/**", "/layui/**","/login","/captcha","/user/**");

    }
    //告诉浏览器哪些请求哪些方法允许方法
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        //设置允许跨域的路径
        registry.addMapping("/**")
                // 设置允许跨域请求的域名
                .allowedOriginPatterns("*")
                // 是否允许cookie
                .allowCredentials(true)
                // 设置允许的请求方式
                .allowedMethods("GET", "POST", "DELETE", "PUT")
                // 设置允许的header属性
                .allowedHeaders("*")
                // 跨域允许时间
                // (当一个请求中可能有多个请求，每个请求都会向服务器询问，如果在3600有多次请求忽略询问，直接访问)
                .maxAge(3600);
    }
}